package com.huabo.monitor.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hbfk.entity.DealUserToken;

import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.FtpUtil;
import com.hbfk.util.ImportOrExportExcelUtil;
import com.hbfk.util.JsonBean;
import com.huabo.monitor.entity.*;
import com.huabo.monitor.service.*;
import com.huabo.monitor.util.ConstClass;
import com.huabo.monitor.util.ExportDoc;
import com.huabo.monitor.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author：yhr
 * @date:2022-08-31 10:51
 * @description:
 */
@RestController
@Slf4j
@Api(value = "评价管理-评价结果", tags = {"评价管理-评价结果所有接口"})
@RequestMapping(value = "/nbkz")
public class PjjgController {


    @Autowired
    TblAssessService tblAssessService;

    @Autowired
    ITblStaffService iTblStaffService;
    @Autowired
    ITblAssessMarkService iTblAssessMarkService;

    @Autowired
    ITblTaskService iTblTaskService;
    @Autowired
    ITblAssesstempleService iTblAssesstempleService;

    @Autowired
    ITblAsseleCategoryService iTblAsseleCategoryService;

    @Autowired
    PjjgService pjjgService;

    @Autowired
    ITblAssesslevelService iTblAssesslevelService;

    @Autowired
    ITblAssessTargetService iTblAssessTargetService;

    @Autowired
    ITblAmorgProblemService iTblAmorgProblemService;
    @Autowired
    ITblAttachmentService iTblAttachmentService;

    @Autowired
    ITblRiskAttWordService iTblRiskAttWordService;

    @Value("${filedir}")
    String filedir;

    @GetMapping(value = "/pjgl/t08_proj_task_result")
    @ApiOperation("评价结果-主页查询")
    public JsonBean initiatePjgl(@ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
                                 @ApiParam(name = "assNumnber", value = "评价编号") @RequestParam(value = "assNumnber", required = false) String assNumnber,
                                 @ApiParam(name = "assName", value = "项目名称") @RequestParam(value = "assName", required = false) String assName,
                                 @ApiParam(name = "startDate", value = "开始时间:格式年-月-日") @RequestParam(value = "startDate", required = false) String startDate,
                                 @ApiParam(name = "startDates", value = "--开始时间") @RequestParam(value = "startDates", required = false) String startDates,
                                 @ApiParam(name = "endDate", value = "结束日期") @RequestParam(value = "endDate", required = false) String endDate,
                                 @ApiParam(name = "endDates", value = "--结束日期") @RequestParam(value = "endDates", required = false) String endDates,
                                 @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        TblStaffUtil staff = DealUserToken.parseUserToken(token);

        IPage<TblAssessVo> iPage = tblAssessService.initiatePjjg(pageNumber, assNumnber, assName, startDate, startDates, endDate, endDates, staff);

        Map<String, Object> mv = new HashMap<>();
        mv.put("assNumnber", assNumnber);
        mv.put("assName", assName);
        mv.put("startDate", startDate);
        mv.put("startDates", startDates);
        mv.put("endDate", endDate);
        mv.put("endDates", endDates);
        mv.put("pageBean", iPage);
        return new JsonBean(200, "success", mv);
    }


    /**
     * 评价最终等级
     *
     * @return
     * @author
     */
    @GetMapping(value = "/pjgl/t08_proj_disp_gd")
    @ApiOperation("评价结果-主页列表-点击评价编号(评价结果-评价)")
    public JsonBean t08_proj_disp_gds(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @ApiParam(name = "assId", value = "assId", defaultValue = "660221") @RequestParam(value = "assId") BigDecimal assId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblAssess assess = this.tblAssessService.getById(assId);
        IPage<TblAssessTargetVo> pageBean = this.pjjgService.getOrgList(assId, pageNumber);
        Map<String, Object> mv = new HashMap<>();
        mv.put("project", assess);
        mv.put("assId", assId);
        mv.put("pageBean", pageBean);

        return new JsonBean(200, "success", mv);
    }

    /**
     * 评价归档 - 评级校正跳转修改
     *
     * @param targetId
     * @param
     * @return
     */
    @ApiOperation("评价结果-评价归档- 评级校正")
    @GetMapping(value = "/pjgl/t08_appr_result_disp")
    public JsonBean t08_appr_result_disp(
            @ApiParam(name = "targetId", value = "targetId", defaultValue = "675438") @RequestParam(value = "targetId") BigDecimal targetId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new HashMap<>();
        if (null != targetId) {
            TblAssessTargetVo assessTarget = this.pjjgService.getMyOneTargetVo(targetId);

            TblStaffUtil staff = DealUserToken.parseUserToken(token);

            QueryWrapper<TblAssesslevel> qw = new QueryWrapper<TblAssesslevel>();
            qw.eq("tblcomany", staff.getCurrentOrg().getOrgid());
            qw.orderByDesc("levellower");


            List<TblAssesslevel> assesslevels = this.iTblAssesslevelService.list(qw);

            mv.put("assessTarget", assessTarget);
            mv.put("assesslevels", assesslevels);


        }

        return new JsonBean(200, "success", mv);
    }

    /**
     * 评价归档-评级校正保存
     *
     * @param targetId
     * @param
     * @param
     * @return
     */
    @ApiOperation("评价归档- 评级校正保存")
    @PostMapping(value = "/pjgl/target_modife")
    public JsonBean target_modife(
            @ApiParam(name = "targetId", value = "targetId", defaultValue = "675438") @RequestParam(value = "targetId") BigDecimal targetId,
            @ApiParam(name = "checkLevel", value = "校正等级", defaultValue = "") @RequestParam(value = "checkLevel", required = false) String checkLevel,
            @ApiParam(name = "checkReason", value = "校正原因", defaultValue = "") @RequestParam(value = "checkReason", required = false) String checkReason,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblAssessTarget assessTarget = this.iTblAssessTargetService.getById(targetId);
        assessTarget.setChecklevel(checkLevel);
        assessTarget.setCheckreason(checkReason);

        iTblAssessTargetService.updateById(assessTarget);
        return t08_appr_result_disp(targetId, token);

    }


    /**
     * 问题-列表
     *
     * @param
     * @param orgid
     * @param orgtype
     * @return
     * @author tangjiajun
     */
    @ApiOperation("评级校正-添加问题-列表")
    @GetMapping(value = "/pjgl/question_list_add")
    public JsonBean question_listQxwt_pj(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @ApiParam(name = "orgid", value = "orgid", defaultValue = "116821") @RequestParam(value = "orgid", required = false) String orgid,
            @ApiParam(name = "orgtype", value = "如果传了orgid则这个可以不传,传值就要传正确") @RequestParam(value = "orgtype", required = false) String orgtype,
            @ApiParam(name = "targetId", value = "targetId", defaultValue = "675438") @RequestParam(value = "targetId") BigDecimal targetId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        //TblProblemService test = SpringContextHolder.getBean("TblProblemService");
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = DealUserToken.parseUserToken(token);
        String number = String.valueOf(pageNumber);

        if (StringUtils.isBlank(orgid)) {
            orgid = staff.getCurrentOrg().getOrgid().toString();
            orgtype = staff.getCurrentOrg().getOrgtype().toString();
        }
        TblOrganization org = this.tblAssessService.queryOrganizationById(new BigDecimal(orgid));
        if (StringUtils.isBlank(orgtype)) {
            orgtype = org.getOrgtype().toString();
        }

        if (number != null && number.length() > 0) {
            pageNumber = Integer.parseInt(number);
        }
        Map<String, Object> mv = new HashMap<>();
        // pageBean = test.findByPageBean(null, null, null, null, null,
        // pageNumber, pageBean.getPageSize(),orgid,orgtype);
        //pageBean = test.findByPageBean(pageNumber, pageBean.getPageSize(), orgid, orgtype);


        mv.put("pageBean", this.pjjgService.findByPageBean(pageNumber, orgid, orgtype));
        mv.put("orgid", orgid);
        mv.put("targetid", targetId);
        mv.put("orgtype", orgtype);
        return new JsonBean(200, "success", mv);
    }


    /**
     * 评价归档 - 评级校正添加问题
     *
     * @param
     * @return
     */
    @ApiOperation("评级校正-添加问题列表-选定添加")
    @PostMapping(value = "/pjgl/add_problem")
    public JsonBean pjgl_addProblem(
            @ApiParam(name = "proid", value = "proid", defaultValue = "476343__b") @RequestParam(value = "proid") String proid,
            @ApiParam(name = "targetid", value = "targetid", defaultValue = "675438") @RequestParam(value = "targetid") BigDecimal targetid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        if (proid != null || targetid != null) {
            //TblAssessTarget assessTarget = this.iTblAssessTargetService.getById(targetid);
            QueryWrapper<TblAmorgProblem> qw = new QueryWrapper<TblAmorgProblem>();
            TblAmorgProblem tblAmorgProblem = new TblAmorgProblem();

            if (proid.indexOf("__b") >= 0) {

                String id = proid.replace("__b", "");
                qw.eq("amorgid", targetid).eq("bugid", id);
                TblAmorgProblem one = this.iTblAmorgProblemService.getOne(qw);
                if (one == null) {
                    tblAmorgProblem.setAmorgid(targetid);
                    tblAmorgProblem.setBugid(new BigDecimal(id));
                    iTblAmorgProblemService.save(tblAmorgProblem);
                }
            }
            if (proid.indexOf("__d") >= 0) {

                String id = proid.replace("__d", "");
                qw.eq("amorgid", targetid).eq("sheetid", id);
                TblAmorgProblem one = this.iTblAmorgProblemService.getOne(qw);
                if (one == null) {
                    tblAmorgProblem.setAmorgid(targetid);
                    tblAmorgProblem.setSheetid(new BigDecimal(id));
                    iTblAmorgProblemService.save(tblAmorgProblem);
                }
            }
            if (proid.indexOf("__f") >= 0) {


                String id = proid.replace("__f", "");
                qw.eq("amorgid", targetid).eq("riskid", id);
                TblAmorgProblem one = this.iTblAmorgProblemService.getOne(qw);
                if (one == null) {
                    tblAmorgProblem.setAmorgid(targetid);
                    tblAmorgProblem.setRiskid(new BigDecimal(id));
                    iTblAmorgProblemService.save(tblAmorgProblem);
                }
            }

        }
        return new JsonBean(200, "sucess", null);
    }

    /**
     * 评价归档 - 评级校正删除问题
     *
     * @param
     * @return
     */
    @ApiOperation("评级校正--删除问题(未测试)")
    @PostMapping(value = "/pjgl/delete_problem")
    public @ResponseBody
    JsonBean pjgl_delete_problem(
            @ApiParam(name = "proid", value = "proid", defaultValue = "476343__b") @RequestParam(value = "proid") String proid,
            @ApiParam(name = "targetid", value = "targetid", defaultValue = "675438") @RequestParam(value = "targetid") BigDecimal targetid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        if (proid != null || targetid != null) {
            QueryWrapper<TblAmorgProblem> qw = new QueryWrapper<TblAmorgProblem>();

            if (proid.indexOf("__b") >= 0) {
                String id = proid.replace("__b", "");
                qw.eq("amorgid", targetid).eq("bugid", id);
            }
            if (proid.indexOf("__d") >= 0) {
                String id = proid.replace("__d", "");
                qw.eq("amorgid", targetid).eq("sheetid", id);
            }
            if (proid.indexOf("__f") >= 0) {
                String id = proid.replace("__f", "");
                qw.eq("amorgid", targetid).eq("riskid", id);
            }
            // 删除
            iTblAmorgProblemService.remove(qw);
        }

        return new JsonBean(200, "sucess", null);
    }


    /**
     * 查看评价结果
     *
     * @return
     */
    @ApiOperation("评价结果-主页-点击结果")
    @GetMapping(value = "/pjgl/t08_proj_initiate_task_result")
    public JsonBean t08_proj_org_result(
            @ApiParam(name = "assId", value = "assId", defaultValue = "675437") @RequestParam(value = "assId") BigDecimal assId,
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = DealUserToken.parseUserToken(token);
        final IPage<TblAssessTargetVo> pageBean = this.pjjgService.findMarkByOrgGroupZuPing(assId, staff.getStaffid(), pageNumber);

        TblAssess assess = this.tblAssessService.getById(assId);

        Map<String, Object> mv = new HashMap<>();
        mv.put("pageBean", pageBean);
        mv.put("project", assess);
        mv.put("assId", assId);

        return new JsonBean(200, "success", mv);

    }

    /**
     * 计算分数---评价对象
     *
     * @param assId
     * @return
     */
    @ApiOperation("评价结果-计算分数")
    @PostMapping(value = "/pjgl/calculate")
    public JsonBean calculate(
            @ApiParam(name = "assId", value = "assId", defaultValue = "675437") @RequestParam(value = "assId") BigDecimal assId,
            @ApiParam(name = "orgid", value = "orgid", defaultValue = "116821") @RequestParam(value = "orgid") BigDecimal orgid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        return this.pjjgService.calculate(assId, orgid);
    }

    /**
     * 评价结果 横向
     *
     * @param
     * @return
     */

    @ApiOperation("评价结果-点击机构-要素明细")
    @GetMapping(value = "/pjgl/t08_proj_organ_diap")
    public JsonBean proj_t08_proj_organ_diap(
            @ApiParam(name = "assId", value = "assId", defaultValue = "675437") @RequestParam(value = "assId") BigDecimal assId,
            @ApiParam(name = "orgid", value = "orgid", defaultValue = "116821") @RequestParam(value = "orgid") BigDecimal orgid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        return this.pjjgService.yaoSuMingXi(assId, orgid);
    }


    @ApiOperation("评价结果-要素明细-详情")
    @GetMapping(value = "/pjgl/info_pjjg")
    public JsonBean info_pjjg(
            @ApiParam(name = "assmarkid", value = "assmarkid", defaultValue = "675440") @RequestParam(value = "assmarkid") BigDecimal assmarkid,
            @ApiParam(name = "asscatid", value = "asscatid", defaultValue = "526527") @RequestParam(value = "asscatid") BigDecimal asscatid,
            @ApiParam(name = "lb", value = "lb", defaultValue = "") @RequestParam(value = "lb", required = false) String lb,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        final List<Map<String, Object>> list = this.pjjgService.getPingJiaXiangQing(assmarkid, asscatid);

        List<TblAttachment> listAtt = new ArrayList<>();
        if (list != null && list.size() > 0) {
            // Object[] o = obj.get(0);

            for (Map<String, Object> map : list) {
                System.out.println(map.get("ASSELEID").getClass());
                if (map.get("ATTID") != null && map.get("ATTID").toString() != "") {
                    TblAttachment att = iTblAttachmentService.getById((BigDecimal) map.get("ATTID"));
                    listAtt.add(att);
                }
            }
        }
        Map<String, Object> mv = new HashMap<>();
        mv.put("obj", list);
        mv.put("listAtt", listAtt);
        mv.put("lb", lb);
        return new JsonBean(200, "success", mv);
    }


    @ApiOperation("评价结果-要素明细-导出word")
    @GetMapping(value = "/pgjg/expWordFile")
    public void expWordFile(
            HttpServletResponse response,
            @ApiParam(name = "assId", value = "assId", defaultValue = "675437") @RequestParam(value = "assId") BigDecimal assId,
            @ApiParam(name = "orgid", value = "orgid", defaultValue = "116821") @RequestParam(value = "orgid") BigDecimal orgid

    ) throws Exception {

        final Map<String, Object> dataMap = this.pjjgService.yaoSuMingXi2(assId, orgid);

        String fileNameStr = "pjjg.doc";
        String folderPath = this.filedir;
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String fileName = folderPath + "/" + uuid + ".doc";
        System.out.println("fileName---" + fileName);
        ExportDoc exp = new ExportDoc();
        exp.createDoc("pgjg.xml", fileName, dataMap);
        // 导出Word
        FileUtil.downLoad(fileName, response, false, fileNameStr);

        FileUtil.deleteFile(fileName);
    }


    /**
     * @Title: pfjg_export @Description: 评价结果--详情，导出评分列表 @param request @param
     * response @return String @throws
     */
    @ApiOperation("评价结果-要素明细-导出excel")
    @GetMapping(value = "/pjgl/ysmx_export")
    public @ResponseBody
    String ysmx_export(
            @ApiParam(name = "assid", value = "assid", defaultValue = "675437") @RequestParam(value = "assid") BigDecimal assid,
            HttpServletResponse response) {

        log.info("内控合规---评价结果---详情---导出Excel");
        response.setContentType("application/binary;charset=UTF-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String("要素明细".getBytes(), "iso-8859-1") + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            List<Object[]> objList = this.pjjgService.ysmxExport(assid);
            String[] titles = {"要素编号", "要素名称", "标准分", "审查要点", "评价分", "评价人", "评价依据", "附件名称"};
            ImportOrExportExcelUtil.exportExcel(titles, objList, outputStream, null);
        } catch (Exception e) {
            log.info("内控合规---评价结果---详情---导出Excel失败");
        }
        return null;
    }


    @ApiOperation("评价结果-预览")
    @GetMapping(value = "/preview")
    public void risk_preview(
            @ApiParam(name = "reportType", value = "reportType", defaultValue = "nkhg") @RequestParam(value = "reportType") String reportType,
            @ApiParam(name = "id", value = "id", defaultValue = "675437") @RequestParam(value = "id") String id,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token,
            HttpServletResponse response) throws Exception {
        TblStaffUtil staff = DealUserToken.parseUserToken(token);


        if (StringUtils.isBlank(reportType)) {
            log.info(staff.getCurrentOrg().getOrgname() + "报告生成type为空");

        }

        TblRiskAttWord trraw = iTblRiskAttWordService.getFile(reportType, staff.getCurrentOrg().getOrgid().toString(), id);
        FtpUtil.pdfPreview(trraw.getFilepath(), trraw.getFilename(), response);

    }

    @ApiOperation("评价结果-预览-判断文件是否存在200:存在 -1:有问题")
    @GetMapping(value = "/isfile")

    public JsonBean isfile(
            @ApiParam(name = "reportType", value = "reportType", defaultValue = "nkhg") @RequestParam(value = "reportType") String reportType,
           @ApiParam(name = "id", value = "id", defaultValue = "675437") @RequestParam(value = "id") String id,
           @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token)
            throws Exception {
        TblStaffUtil staff = DealUserToken.parseUserToken(token);
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        boolean bool = false;

        if (StringUtils.isBlank(reportType)) {
            log.info(staff.getCurrentOrg().getOrgname() + "报告生成type为空");
            return new JsonBean(-1,staff.getCurrentOrg().getOrgname() + "报告生成type为空",-1);
        }

        TblRiskAttWord trraw = iTblRiskAttWordService.getFile(reportType, staff.getCurrentOrg().getOrgid().toString(), id);
        if (trraw == null) {
            return new JsonBean(-1,"error",-1);
        }
        System.out.println(trraw.getFilepath());
        bool = FtpUtil.isFTPFileExistByFilePath( trraw.getFilepath());
        System.out.println(bool);
        if (bool) {
            return new JsonBean(200,"文件"+trraw.getFilepath()+"存在",0);
        } else {
            return new JsonBean(-1,"文件不存在",-1);
        }

    }
    @ApiOperation("评价结果-生成报告(涉及太多远程环境,功能无法实现)")
    @GetMapping(value = "/risk_generate_report")
    public JsonBean risk_generate_report(
            @ApiParam(name = "reportType", value = "reportType", defaultValue = "nkhg") @RequestParam(value = "reportType") String reportType,
            @ApiParam(name = "id", value = "id", defaultValue = "675437") @RequestParam(value = "id") String id,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token)
            throws Exception {

        return new JsonBean(-1,"功能未实现",null);
    }

}

